from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from app.core.config import settings

# 创建异步数据库引擎
engine = create_async_engine(
    settings.DATABASE_URL,
    echo=True,
)

# 创建异步会话工厂
AsyncSessionLocal = sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False
)


async def get_db():
    """
    获取数据库会话

    用于依赖注入，提供异步数据库会话
    如果连接失败，会抛出异常
    """
    async with AsyncSessionLocal() as session:
        try:
            yield session
        except Exception as e:
            # 在实际生产环境中，可以记录日志
            # logger.error(f"Database session error: {e}")
            raise


